package model

import (
	"gitee.com/buddyxiao/ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Article struct {
	gorm.Model
	Category Category `gorm:"foreignKey:Cid" json:"category"`
	Title    string   `gorm:"type:varchar(100);not null" json:"title"`
	Cid      int      `gorm:"type:int;not null" json:"cid"`
	Desc     string   `gorm:"type:varchar(200)" json:"desc"`
	Content  string   `gorm:"type:longtext" json:"content"`
	Img      string   `gorm:"type:varchar(100)" json:"img"`
}

// CreateArticle 新增文章
func CreateArticle(data *Article) (code int) {
	if db.Create(data).Error != nil {
		code = errmsg.ERROR
		return
	}
	code = errmsg.SUCCESS
	return
}

// GetArticle 查询单个文章
func GetArticle(id int) (*Article, int) {
	var article = new(Article)
	if db.Preload("Category").First(article, id).Error != nil {
		return nil, errmsg.ERROR_ARTICLE_NOT_EXIST
	}
	return article, errmsg.SUCCESS
}

// GetArticles 查询文章列表
func GetArticles(title string, pageNum, pageSize int) ([]Article, int, int) {
	offsetValue := (pageNum - 1) * pageSize
	if pageNum == -1 {
		offsetValue = -1 // 不做分页处理
	}
	var articles []Article
	var total int64
	var err error = nil
	if title == "" {
		db.Model(&Article{}).Count(&total)
		err = db.Preload("Category").Limit(pageSize).Offset(offsetValue).Find(&articles).Error
	} else {
		db.Model(&Article{}).Where("title like concat('%',?,'%')", title).Count(&total)
		err = db.Preload("Category").Where("title like concat('%',?,'%')", title).Limit(pageSize).Offset(offsetValue).Find(&articles).Error
	}
	if err != nil {
		return nil, errmsg.ERROR, 0
	}
	return articles, errmsg.SUCCESS, int(total)
}

// GetAllArticleOnCategory 查询分类下的所有文章
func GetAllArticleOnCategory(id, pageNum, pageSize int) ([]Article, int, int) {
	offsetValue := (pageNum - 1) * pageSize
	if pageNum == -1 {
		offsetValue = -1 // 不做分页处理
	}
	var articles []Article
	var total int64
	db.Model(&Article{}).Where("cid = ?", id).Count(&total)
	if db.Preload("Category").Where("cid = ?", id).Limit(pageSize).Offset(offsetValue).Find(&articles).Error != nil {
		return nil, errmsg.ERROR_CATEGORY_NOT_EXIST, 0
	}
	return articles, errmsg.SUCCESS, int(total)
}

// EditArticle 编辑文章
func EditArticle(id int, data *Article) int {
	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	maps["cid"] = data.Cid
	maps["desc"] = data.Desc
	maps["content"] = data.Content
	maps["img"] = data.Img
	if db.Model(&Article{}).Where("id=?", id).Updates(maps).Error != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// DeleteArticle 删除文章
func DeleteArticle(id int) int {
	if db.Delete(&Article{}, id).Error != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
